'use client';

import React, { useRef } from 'react';
import {
  Modal,
  Form,
  Input,
  Select,
  Button,
  Upload,
  Message,
  Space,
} from '@arco-design/web-react';
import { IconUpload, IconPlus } from '@arco-design/web-react/icon';

const FormItem = Form.Item;
const Option = Select.Option;

interface ImportModelModalProps {
  visible: boolean;
  onClose: () => void;
  onSubmit: (values: any) => void;
}

export default function ImportModelModal({ 
  visible, 
  onClose, 
  onSubmit 
}: ImportModelModalProps) {
  const [form] = Form.useForm();
  const uploadRef = useRef<any>(null);

  const handleSubmit = async () => {
    try {
      const values = await form.validate();
      
      // 获取上传的文件
      const uploadedFiles = uploadRef.current?.getUploadedFiles?.() || [];
      
      if (uploadedFiles.length === 0) {
        Message.error('请上传模型文件');
        return;
      }

      const formData = {
        ...values,
        files: uploadedFiles,
      };

      onSubmit(formData);
      handleReset();
      onClose();
      Message.success('模型导入成功');
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleReset = () => {
    form.resetFields();
    uploadRef.current?.clearFiles?.();
  };

  const handleCancel = () => {
    handleReset();
    onClose();
  };

  const uploadProps = {
    multiple: false,
    accept: '.pkl,.pth,.onnx,.h5,.pb,.tflite',
    beforeUpload: (file: File) => {
      const isValidType = /\.(pkl|pth|onnx|h5|pb|tflite)$/.test(file.name);
      if (!isValidType) {
        Message.error('只支持 .pkl, .pth, .onnx, .h5, .pb, .tflite 格式的模型文件');
        return false;
      }
      
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        Message.error('文件大小不能超过 100MB');
        return false;
      }
      
      return true;
    },
    onChange: (fileList: any) => {
      console.log('文件列表变化:', fileList);
    },
  };

  return (
    <Modal
      title="导入模型"
      visible={visible}
      onCancel={handleCancel}
      maskClosable={false}
      onOk={handleSubmit}
      okText="确认导入"
    >
      <Form
        form={form}
        autoComplete='off'
        layout='vertical'
      >
        <FormItem
          label="模型信息"
          field="name"
          rules={[
            { required: true, message: '请输入模型信息' },
            { minLength: 2, message: '模型信息至少2个字符' },
          ]}
        >
          <Input 
            placeholder="请输入模型名称和描述信息" 
            maxLength={100}
            showWordLimit
          />
        </FormItem>

        <FormItem
          label="类型"
          field="type"
          rules={[
            { required: true, message: '请选择模型类型' }
          ]}
        >
          <Select placeholder="请选择模型类型">
            <Option value="人员安全">人员安全</Option>
            <Option value="环境巡视">环境巡视</Option>
            <Option value="设备运检I">设备运检I</Option>
            <Option value="设备运检S">设备运检S</Option>
            <Option value="large">大模型</Option>
            <Option value="small">小模型</Option>
          </Select>
        </FormItem>

        <FormItem
          label="架构"
          field="architecture"
          rules={[
            { required: true, message: '请输入模型架构' },
            { minLength: 2, message: '架构名称至少2个字符' },
          ]}
        >
          <Input 
            placeholder="如: ResNet50, YOLO, Transformer 等" 
            maxLength={50}
          />
        </FormItem>

        <FormItem
          label="版本"
          field="version"
          rules={[
            { required: true, message: '请输入版本号' },
            { 
              validator: (value: string) => {
                const pattern = /^v?\d+\.\d+(\.\d+)?$/;
                if (!pattern.test(value)) {
                  return Promise.reject('版本号格式不正确，如: v1.0 或 1.0.0');
                }
                return Promise.resolve();
              }
            },
          ]}
        >
          <Input 
            placeholder="如: v1.0, 1.2.3 等" 
            maxLength={20}
          />
        </FormItem>

        <FormItem
          label="模型文件"
          field="files"
          rules={[
            { required: true, message: '请上传模型文件' }
          ]}
        >
          <Upload
            ref={uploadRef}
            {...uploadProps}
            drag
            tip="支持 .pkl, .pth, .onnx, .h5, .pb, .tflite 格式，文件大小不超过 100MB"
          >
            <div className="flex flex-col items-center justify-center py-8">
              <IconUpload className="text-4xl text-gray-400 mb-2" />
              <div className="text-sm text-gray-600">
                点击或拖拽文件到此区域上传
              </div>
            </div>
          </Upload>
        </FormItem>
      </Form>
    </Modal>
  );
} 